package com.xindaoapp.happypet.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.adapter.UserListAdapter;
import com.xindaoapp.happypet.bean.User;
import com.xindaoapp.happypet.bean.UserEntity;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.xdConfig;

public class UserFragment extends XDBaseFragment implements OnClickListener, OnItemClickListener {

    private EditText et_search;
    private TextView iv_search;
    private ListView listView;

    private String searchKey = "";
    private Context mContext;

    private UserListAdapter searchAdapter;
    private final List<User> mList = new ArrayList<User>();

    private ProgressDialog progressDialog;

    public static UserFragment Instance(Bundle args) {
        final UserFragment f = new UserFragment();

        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return mView = inflater.inflate(R.layout.fragment_search_user, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initUi() {

        mContext = getActivity();

        et_search = (EditText) findViewById(R.id.et_search);
        iv_search = (TextView) findViewById(R.id.iv_search);
        listView = (ListView) findViewById(R.id.listView);

        searchAdapter = new UserListAdapter(mContext, mList, R.layout.item_search_user_list);
        // listView.setAdapter(searchAdapter);

        et_search.addTextChangedListener(watcher);
        iv_search.setOnClickListener(this);
        listView.setOnItemClickListener(this);

    }

    private void update() {
        searchAdapter.notifyDataSetChanged();
        listView.setAdapter(searchAdapter);
    }

    private String word;

    private void getSearchData() {

        word = et_search.getText().toString();

        if (TextUtils.isEmpty(word)) {
            Toast.makeText(mContext, R.string.empt_ykey, 0).show();
            return;
        }

        if (CommonUtil.checkNetState(mContext)) {

            progressDialog = ProgressDialog.show(mContext, null, "获取数据中...", true);
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(true);

            RequestParams params = new RequestParams();
            params.put("username", word);

            XDHttpClient.get(xdConfig.SEARCHUSER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    if (!TextUtils.isEmpty(content)) {

                        UserEntity entity = null;
                        try {
                            entity = JSON.parseObject(content, UserEntity.class);

                            if (entity.getResult().equals("0")) {
                                if (entity.getUserlist().size() == 0) {
                                    Toast.makeText(mContext, "没有搜索到相关用户!", Toast.LENGTH_SHORT)
                                            .show();
                                } else {
                                    mList.addAll(entity.getUserlist());
                                    update();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        progressDialog.cancel();
                    } else {
                        progressDialog.cancel();
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    progressDialog.cancel();
                    Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
                }
            });
        } else {
            Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    /** 隐藏键盘 */
    protected final void hideKeyBoard() {
        InputMethodManager inputManager =
                (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getActivity().getWindow().getDecorView()
                .getWindowToken(), 0);
    }

    private final TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            searchKey = et_search.getText().toString();

            if (searchKey.equals("")) {
                Toast.makeText(getActivity(), "数据木有啦", Toast.LENGTH_SHORT).show();
                mList.clear();
                searchAdapter.notifyDataSetChanged();
                listView.setAdapter(searchAdapter);
            }

        }
    };

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // Intent intent = new Intent(getActivity(), OtherActivity.class);
        // User user = mList.get(arg2);
        // intent.putExtra("uid", user.uid);
        // intent.putExtra("name", user.username);
        // intent.putExtra("face", user.userface);
        // startActivity(intent);
        User user = mList.get(arg2);
        Intent intent =
                new Intent(getActivity(), com.xindaoapp.happypet.activity.MainActivity.class);
        intent.putExtra(Constants.KEY_SKIP_CLASS_NAME, UserInfoFragment.class.getCanonicalName());
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_UID, user.uid);
        bundle.putString(Constants.KEY_USERNAME, user.username);
        bundle.putString(Constants.KEY_USERFACE, user.userface);
        intent.putExtra(Constants.KEY_BUNDLE, bundle);
        getActivity().startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                mList.clear();
                hideKeyBoard();
                getSearchData();
                break;

            default:
                break;
        }
    }

}
